<template>
  <transition name="el-zoom-in-center">
    <div class="jsbos-preview-main content_box flow-form-main">
      <div class="jsbos-common-page-header">
        <el-page-header
          @back="goBack"
          :content="!dataForm.id ? '新建' : isDetail ? '详情' : '编辑'"
        />
        <div class="options">
          <el-button type="primary" size="mini" @click="dataFormSubmit(2)" plain
            >保 存</el-button
          >
          <el-button type="primary" size="mini" @click="dataFormSubmit(1)"
            >发 布</el-button
          >
          <el-button @click="goBack" size="mini">返 回</el-button>
        </div>
      </div>
      <div class="main" v-loading="listLoading">
        <el-row :gutter="15" class="">
          <el-form
            v-loading="loading"
            ref="elForm"
            :model="dataForm"
            :rules="rules"
            size="small"
            label-width="100px"
            label-position="right"
          >
            <template v-if="!loading">
              <el-card class="box-card" shadow="never">
                <div slot="header" class="clearfix">
                  <span class="header">&nbsp;</span>&nbsp;&nbsp;
                  <span>基本信息</span>
                </div>
                <el-col :span="24">
                  <el-form-item label="抽奖名称" prop="title">
                    <el-input
                      v-model="dataForm.title"
                      placeholder="请输入抽奖名称（50字以内）"
                      :maxlength="50"
                      clearable
                      :style="{ width: '100%' }"
                    >
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="抽奖形式" prop="drawType">
                    <el-radio-group v-model="dataForm.drawType" size="small">
                      <el-radio
                        v-for="(item, index) in drawTypeOptions"
                        :key="index"
                        :label="item.enCode"
                        :disabled="item.disabled"
                      >
                        {{ item.fullName }}
                      </el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="抽奖时间" prop="time" required>
                    <el-date-picker
                      value-format="yyyy-MM-dd"
                      style="width: 50%"
                      v-model="dataForm.time"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                    >
                    </el-date-picker>
                    <!-- <el-date-picker
                    v-model="dataForm.startTime"
                    placeholder="请选择"
                    clearable
                    :style="{ width: '100%' }"
                    type="date"
                    format="yyyy-MM-dd"
                    value-format="timestamp"
                  >
                  </el-date-picker> -->
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="每人能抽" prop="enableNumber">
                    <el-input-number
                      v-model="dataForm.enableNumber"
                      placeholder="数字文本"
                      :step="1"
                      :min="1"
                    >
                    </el-input-number>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="抽奖活动要求" prop="drawRequire">
                    <el-input
                      v-model="dataForm.drawRequire"
                      placeholder="请输入"
                      :style="{ width: '100%' }"
                      true
                      type="textarea"
                      :autosize="{ minRows: 4, maxRows: 4 }"
                    >
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-card>
              <el-card class="box-card2" shadow="never">
                <div slot="header" class="clearfix">
                  <span class="header">&nbsp;</span>&nbsp;&nbsp;
                  <span>奖项设置</span>
                </div>
                <el-col :span="24">
                  <el-form-item label-width="0">
                    <el-table :data="dataForm.cmsAwardTypeList" size="mini">
                      <el-table-column
                        type="index"
                        width="50"
                        label="序号"
                        align="center"
                      />
                      <el-table-column prop="prizeName" label="奖品名称">
                        <template slot="header">
                          <span class="required-sign">*</span>奖品名称
                        </template>
                        <template slot-scope="scope">
                          <el-input
                            v-model="scope.row.prizeName"
                            placeholder="请输入"
                            clearable
                            :style="{ width: '100%' }"
                          >
                          </el-input>
                        </template>
                      </el-table-column>
                      <el-table-column prop="prizeNumber" label="奖品数量">
                        <template slot="header">
                          <span class="required-sign">*</span>奖品数量
                        </template>
                        <template slot-scope="scope">
                          <el-input
                            v-model="scope.row.prizeNumber"
                            placeholder="请输入"
                            clearable
                            :style="{ width: '100%' }"
                          >
                          </el-input>
                        </template>
                      </el-table-column>
                      <el-table-column prop="everyTime" label="每次抽几人">
                        <template slot="header">
                          <span class="required-sign">*</span>每次抽几人
                        </template>
                        <template slot-scope="scope">
                          <el-input
                            v-model="scope.row.everyTime"
                            placeholder="请输入"
                            clearable
                            :style="{ width: '100%' }"
                          >
                          </el-input>
                        </template>
                      </el-table-column>
                      <el-table-column prop="prizeImage" label="奖品图片">
                        <template slot="header">
                          <span class="required-sign">*</span>奖品图片
                        </template>
                        <template slot-scope="scope">
                          <UploadImg
                            v-model="scope.row.prizeImage"
                            sizeUnit="MB"
                            :limit="1"
                          >
                          </UploadImg>
                        </template>
                      </el-table-column>
                      <el-table-column label="操作" width="50">
                        <template slot-scope="scope">
                          <el-button
                            v-if="dataForm.cmsAwardTypeList.length > 1"
                            size="mini"
                            type="text"
                            class="jsbos-table-delBtn"
                            @click="delCmsAwardTypeList(scope.$index)"
                          >
                            删除
                          </el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                    <div class="table-actions" @click="addCmsAwardTypeList()">
                      <el-button type="text" icon="el-icon-plus"
                        >添加</el-button
                      >
                    </div>
                  </el-form-item>
                </el-col>
              </el-card>
            </template>
          </el-form>
        </el-row>
      </div>
    </div>
  </transition>
</template>
<script>
import request from "@/utils/request";
import { getDataInterfaceRes } from "@/api/systemData/dataInterface";

export default {
  components: {},
  props: [],
  data() {
    return {
      listLoading: false,
      visible: false,
      loading: false,
      isDetail: false,
      dataForm: {
        publish: "",
        time: [],
        title: "",
        drawType: "",
        startTime: "",
        enableNumber: "",
        drawRequire: "",
        detail: "",
        cmsAwardTypeList: [],
      },
      rules: {
        title: [
          {
            required: true,
            message: "请输入抽奖名称（50字以内）",
            trigger: "blur",
          },
        ],
        time: [
          {
            required: true,
            message: "请选择抽奖时间",
            trigger: "change",
          },
        ],
      },
      drawTypeOptions: [],
    };
  },
  computed: {},
  watch: {},
  created() {
    this.getDrawTypeOptions();
  },
  mounted() {},
  methods: {
    cmsAwardTypeExist() {
      let isOk = true;
      for (let i = 0; i < this.dataForm.cmsAwardTypeList.length; i++) {
        const e = this.dataForm.cmsAwardTypeList[i];
        if (!e.prizeName) {
          this.$message({
            message: "奖品名称不能为空",
            type: "error",
            duration: 1000,
          });
          isOk = false;
          break;
        }
        if (!e.prizeNumber) {
          this.$message({
            message: "奖品数量不能为空",
            type: "error",
            duration: 1000,
          });
          isOk = false;
          break;
        }
        if (!e.everyTime) {
          this.$message({
            message: "每次抽几人不能为空",
            type: "error",
            duration: 1000,
          });
          isOk = false;
          break;
        }
        if (!e.prizeImage) {
          this.$message({
            message: "奖品图片不能为空",
            type: "error",
            duration: 1000,
          });
          isOk = false;
          break;
        }
      }
      return isOk;
    },
    getDrawTypeOptions() {
      this.listLoading = true;
      this.$store
        .dispatch("base/getDictionaryData", {
          encode: "drawType",
        })
        .then((res) => {
          this.drawTypeOptions = res;
          this.listLoading = false;
        });
    },
    clearData(data) {
      for (let key in data) {
        if (data[key] instanceof Array) {
          data[key] = [];
        } else if (data[key] instanceof Object) {
          this.clearData(data[key]);
        } else {
          data[key] = "";
        }
      }
    },
    init(id, isDetail) {
      this.dataForm.id = id || 0;
      this.visible = true;
      this.isDetail = isDetail || false;
      this.$nextTick(() => {
        this.$refs["elForm"].resetFields();
        if (this.dataForm.id) {
          this.loading = true;
          request({
            url: "/api/cms/CmsAwardActivity/" + this.dataForm.id,
            method: "get",
          }).then((res) => {
            this.dataInfo(res.data);
            this.loading = false;
          });
        } else {
          this.clearData(this.dataForm);
          this.dataForm.drawType = "1";
          this.dataForm.enableNumber = "1";
          this.dataForm.drawRequire =
            "欢迎大家来参加活动，奖品多多！惊喜多多，快来试试吧~";
        }

        let item = {
          prizeName: undefined,
          prizeNumber: undefined,
          everyTime: undefined,
          prizeImage: undefined,
        };
        this.dataForm.cmsAwardTypeList.push(item);
      });
      this.$store.commit("generator/UPDATE_RELATION_DATA", {});
    },
    // 表单提交
    dataFormSubmit(status) {
      this.$refs["elForm"].validate((valid) => {
        if (valid) {
          if (!this.cmsAwardTypeExist()) return;
          this.dataForm.publish = status;
          this.request();
        }
      });
    },
    request() {
      var _data = this.dataList();
      if (!this.dataForm.id) {
        request({
          url: "/api/cms/CmsAwardActivity",
          method: "post",
          data: _data,
        }).then((res) => {
          this.$message({
            message: res.msg,
            type: "success",
            duration: 1000,
            onClose: () => {
              this.visible = false;
              this.$emit("refresh", true);
            },
          });
        });
      } else {
        request({
          url: "/api/cms/CmsAwardActivity/" + this.dataForm.id,
          method: "PUT",
          data: _data,
        }).then((res) => {
          this.$message({
            message: res.msg,
            type: "success",
            duration: 1000,
            onClose: () => {
              this.visible = false;
              this.$emit("refresh", true);
            },
          });
        });
      }
    },
    addCmsAwardTypeList() {
      let item = {
        prizeName: undefined,
        prizeNumber: undefined,
        everyTime: undefined,
        prizeImage: undefined,
      };
      this.dataForm.cmsAwardTypeList.push(item);
    },
    delCmsAwardTypeList(index) {
      this.dataForm.cmsAwardTypeList.splice(index, 1);
    },
    dataList() {
      var _data = JSON.parse(JSON.stringify(this.dataForm));
      _data.startTime = _data.time[0];
      _data.endTime = _data.time[1];
      for (let i = 0; i < _data.cmsAwardTypeList.length; i++) {
        _data.cmsAwardTypeList[i].prizeImage = JSON.stringify(
          _data.cmsAwardTypeList[i].prizeImage
        );
      }

      return _data;
    },
    dataInfo(dataAll) {
      let _dataAll = dataAll;
      var time = [];
      time[0] = _dataAll.startTime;
      time[1] = _dataAll.endTime;
      _dataAll.time = time;

      console.log("1111111111111111111", _dataAll);
      for (let i = 0; i < _dataAll.cmsAwardTypeList.length; i++) {
        _dataAll.cmsAwardTypeList[i].prizeImage = JSON.parse(
          _dataAll.cmsAwardTypeList[i].prizeImage
        );
      }
      this.dataForm = _dataAll;
    },
    goBack() {
      this.$emit("refresh", true);
    },
  },
  //返回
};
</script>
<style lang="scss" scoped>
.box-card {
  padding: 20px 150px 20px 150px;
}

.box-card2 {
  padding: 20px 150px 20px 150px;
  margin-bottom: 50px;
}

.clearfix {
  font-size: 16px;
  color: black;
}
.header {
  background: #18a6f4;
}

.content_box {
  >>> .el-card__header {
    border: none !important;
  }

  .el-card {
    border: 0px;
    padding: 16px 150px 0px 150px;
  }
}
</style>
